export default {
	/* 开启命名空间才能使用仓库 */
	namespaced:true,
	state:()=>({
		/* 储存购物车每个商品的信息对象，包含{goods_id,goods_name,goods_price,goods_count,goods_small_log,goods_state} */
		cart:JSON.parse(uni.getStorageSync('cart')||'[]')
	}),
	//方法
	mutations:{
		addTocart(state,good){
			const findResult=state.cart.find((x)=>x.goods_id===good.goods_id)
			console.log(findResult)
			if(!findResult){
				state.cart.push(good)
			}
			else{
				findResult.goods_count++
			}
			/* 持久化存储 */
			this.commit('my_cart/saveTocart')
		},
		saveTocart(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		/*更新购物车商品的勾选状态 */
		updateState(state,good){
			const findResult=state.cart.find((x)=>x.goods_id===good.goods_id)
			if(findResult){
				findResult.goods_state=good.goods_state
			}
			/* ?????????? */
			this.commit('my_cart/saveTocart')
		},
		/*更新购物车商品数量 */
		updateCount(state,good){
			const findResult=state.cart.find((x)=>x.goods_id===good.goods_id)
			if(findResult){
				findResult.goods_count=good.goods_count
			}
			/* ?????????? */
			this.commit('my_cart/saveTocart')
		},
		saveTocart(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		removeGoodsId(state,goods_id){
			state.cart=state.cart.filter(x=>x.goods_id!==goods_id)
			this.commit('my_cart/saveTocart')
		},
		updateAllGoodsState(state,updatestate){
			state.cart.forEach(x=>x.goods_state=updatestate)
			this.commit('my_cart/saveTocart')
		}
	},
	//属性
	getters:{
		/* 购物车商品的数量 */
		total(state){
			/* let c=0
			state.cart.forEach(x=>c+=x.goods_count)
			return c */
			return state.cart.reduce((total,item)=>total+=item.goods_count,0)
		},
		/* 购物车已勾选的数量 */
		checkedCount(state){
			return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
		},
		checkedGoodsAmount(state){
			return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
		}
	}
}